package fpt.edu.vn.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/* 
 * CompareAction.java 
 *  
 * 0.1
 * 
 * 10/15/2012 
 *  
 * Copyright notice 
 *  
 * Modification Logs: 
 *   DATE        AUTHOR      DESCRIPTION 
 *  -------------------------------------------------------- 
 *  15-Oct-2012  ThuongND    Create new 
 */
public class CompareAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	private InputStream inputStream;

	private int topicId;

	Map<String, Object> session;

	public String execute() {

		session = ActionContext.getContext().getSession();
		int iNumber = 0;
		if (session.containsKey("number")) {
			StringBuilder topicIds = (StringBuilder) session.get("topicIds");
			String sTopicIds = topicIds.toString();
			Integer number = (Integer) session.get("number");
			if (sTopicIds.contains("" + topicId)) {
				session.put("number", number);
			} else {
				if (number >= 3) {
					number = 3;
				} else {
					number = number + 1;
					topicIds.append(topicId).append(",");
					session.put("topicIds", topicIds);
					session.put("number", number);
				}
			}

			iNumber = number;
		} else {
			iNumber = 1;
			session.put("number", 1);
			StringBuilder topicIds = new StringBuilder();
			topicIds.append(topicId).append(",");
			session.put("topicIds", topicIds);
		}
		StringBuilder stbtemp = new StringBuilder();
		if (iNumber >= 3) {
			iNumber = 3;
			stbtemp.append(iNumber);
		} else {
			stbtemp.append(iNumber);
		}

		inputStream = toUTF8InputStream(stbtemp.toString());
		return SUCCESS;

	}

	public static InputStream toUTF8InputStream(String str) {
		InputStream is = null;
		try {
			is = new ByteArrayInputStream(str.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// UTF-8 should always be supported
			throw new AssertionError();
		}
		return is;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public int getTopicId() {
		return topicId;
	}

	public void setTopicId(int topicId) {
		this.topicId = topicId;
	}

}
